package com.tz.example.single;

import java.lang.reflect.Constructor;

/**
 * 静态内部类懒汉式单例
 * 特点：
 * 1.线程安全，jvm在加载该内部类的时候创建对象，不存在多线程问题
 * 2.可以通过反射破解
 * 3.必需要调getInstance()方法时才会加载内部类，对会new一个实例对象，实现了延迟加载
 * 4.获取和创建过程都没同步锁，不存在多线程下的同步开销问题
 * @author zhangyuetao
 */
public class StaticInnerClassLazySingle {
    private String from;

    public String getFrom() {
        return from;
    }

    private StaticInnerClassLazySingle(String from) {
        this.from = from;
        System.out.println("--create-from:" + from);
    }

    private static class InnerHolder {
        private static final StaticInnerClassLazySingle SINGLE = new StaticInnerClassLazySingle("静态内部类");
    }

    public static StaticInnerClassLazySingle getInstance() {
        return InnerHolder.SINGLE;
    }

    public static void main(String[] args)throws Exception {
        //多线程跑
        for (int i = 0; i < 10; i++) {
            new Thread(){
                @Override
                public void run() {
                    StaticInnerClassLazySingle instance = StaticInnerClassLazySingle.getInstance();
                    System.out.println(instance.toString()+"---from:"+instance.getFrom());
                }
            }.start();
        }
        //反射创建
        Constructor<StaticInnerClassLazySingle> declaredConstructor = StaticInnerClassLazySingle.class.getDeclaredConstructor(String.class);
        declaredConstructor.setAccessible(Boolean.TRUE);
        StaticInnerClassLazySingle instance2 = declaredConstructor.newInstance("反射");
        //打印hasCode
        System.out.println(instance2.toString()+"---from:"+instance2.getFrom());
    }
}
